import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import '@/common/js/permissions'
//axios
import axios from 'axios'
//配置axios的全局基本路径
axios.defaults.baseURL='http://localhost:8080/'
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios

import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
// import NProgress from 'nprogress'
// import 'nprogress/nprogress.css'
import routes from './routes'
// import Mock from './mock'
// Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

const router = new VueRouter({
  routes
})

//前端的路由拦截器
router.beforeEach((to, from, next) => {
  if (to.path == '/login' || to.path == '/register') {  //如果是访问登录和注册页面，直接放行
    next()//放行
  }else{    //如果是访问其他页面就判断是否登录。如果登录了，就允许方法，未登录就跳转登录页面（通过sessionStorage里面的token
    let token = sessionStorage.getItem("token")
    if(token){
      next()
    }else {
      next({ path: '/login' })
    }
  }
})

//前置拦截器
axios.interceptors.request.use(config=>{
  //主要任务就是让每一次请求头都携带token
  let token =  sessionStorage.getItem("token");
  // console.log(token)
  if(token){
    config.headers['Token']=token;
  }
  return config;
},error => {
  Promise.reject(error);
})

//2 使用axios后置拦截器，处理没有登录请求
axios.interceptors.response.use(result=>{
  //将后端传回的token设置到sessionStorage
  if(result.data.success && result.data.msg =='userLogin'){
    sessionStorage.setItem("token",result.data.data.token)
    sessionStorage.setItem("employee",JSON.stringify(result.data.data.logininfo))
    sessionStorage.setItem("user",JSON.stringify(result.data.data.user))
    sessionStorage.setItem("menus",JSON.stringify(result.data.data.menus))
    sessionStorage.setItem("permissions",JSON.stringify(result.data.data.permissions))
  }

  if(!result.data.success && result.data.msg == 'noPermission' ){
    alert("您无操作权限！")
  }

  if(!result.data.success && result.data.msg == 'noLogin' ){
    sessionStorage.removeItem("token")
    sessionStorage.removeItem("employee")
    sessionStorage.removeItem("user")
    sessionStorage.removeItem("permissions")
    sessionStorage.removeItem("menus")
    routes.push({ path: '/login' })
  }
  return result;//一定要返回
},error => {
  Promise.reject(error);
})

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

